<template>
  <div ref="chart" style="width: 100%; height: 400px;"></div>
</template>

<script>
import * as echarts from 'echarts';

export default {
  props: {
    lineList: {
      type: Array,
      required: true
    }
  },
  watch: {
    // 当 lineList 发生变化时，重新绘制图表
    lineList(newVal) {
      if (newVal && newVal.length > 0) {
        this.updateChart(newVal);
      }
    }
  },
  mounted() {
    // 初次加载时，如果数据已经传递进来，则初始化图表
    if (this.lineList && this.lineList.length > 0) {
      this.updateChart(this.lineList);
    }
  },
  methods: {
    updateChart(lineList) {
      // 初始化图表实例
      const chart = echarts.init(this.$refs.chart);

      // 使用 substring 截取时间部分
      const dates = lineList[0].map(item => item.date.substring(11)); // 截取从索引 11 开始的子串，即 "00:00"

      // 构建每一组数据的 series
      const seriesData = lineList.map(group => group.map(item => item.totalCount));

      // 配置项
      const option = {
        xAxis: {
          type: 'category',
          data: dates
        },
        yAxis: {
          type: 'value',
          min: 0,
          max: 30,
          data: ['5','10','15','20','25','30']
        },
        series: seriesData.map(data => ({
          data: data,
          type: 'line',
          smooth: true
        }))
      };

      // 设置图表的配置项
      chart.setOption(option);

      // 监听窗口变化，调整图表大小
      window.addEventListener('resize', () => {
        chart.resize();
      });
    }
  }
};
</script>

<style scoped>
#app {
  text-align: center;
  margin-top: 50px;
}
</style>
